package com.zhang.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhang.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @title: 跳出行为过滤
 * @author: zhang
 * @date: 2022/5/8 16:29
 */
public class DwdTrafficUserJumpDetail {
    public static void main(String[] args) throws Exception {
        // TODO 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        // TODO 从kafka读取数据转换为JSON格式，提取时间戳和分配水位线
        String topic = "dwd_traffic_page_log";
        String groupId = "Dwd_Traffic_UserJump_Detail";
        KeyedStream<JSONObject, String> kafkaWMDS = env
                .addSource(MyKafkaUtil.getKafkaConsumer(topic, groupId))
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                                    @Override
                                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                        return element.getLong("ts");
                                    }
                                })
                )
                .keyBy(data -> data.getJSONObject("common").getString("mid"));

        // TODO 定义模式序列
        Pattern<JSONObject, JSONObject> pattern = Pattern.<JSONObject>begin("first")
                .where(new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        return value.getJSONObject("page").getString("last_page_id") == null;
                    }
                })
                .next("second")
                .where(new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        return value.getJSONObject("page").getString("last_page_id") == null;
                    }
                })
                .within(Time.seconds(10L));
        // TODO 将模式序列作用到流上
        PatternStream<JSONObject> patternStream = CEP.pattern(kafkaWMDS, pattern);

        // TODO 提取超时事件和匹配事件
        OutputTag<JSONObject> timeoutTag = new OutputTag<JSONObject>("time-out") {
        };
        SingleOutputStreamOperator<JSONObject> selectDS = patternStream
                .select(
                        timeoutTag,
                        new PatternTimeoutFunction<JSONObject, JSONObject>() {
                            @Override
                            public JSONObject timeout(Map<String, List<JSONObject>> map, long timeoutTimestamp) throws Exception {
                                return map.get("first").get(0);
                            }
                        },
                        new PatternSelectFunction<JSONObject, JSONObject>() {
                            @Override
                            public JSONObject select(Map<String, List<JSONObject>> map) throws Exception {
                                return map.get("first").get(0);
                            }
                        }
                );

        // TODO 提取侧输出流数据，并合并两个流数据，发送到kafka
        selectDS.print(">>>>>>");
        selectDS.getSideOutput(timeoutTag).print("<<<<<<<<");
        DataStream<JSONObject> resultDS = selectDS.getSideOutput(timeoutTag).union(selectDS);
        //resultDS.print(">>>>>>");

        // TODO 启动任务
        env.execute("DwdTrafficUserJumpDetail");
    }
}
